package com.pzhuweb.sgblog.runner;

import com.pzhuweb.sgblog.domain.entity.Article;
import com.pzhuweb.sgblog.service.ArticleService;
import com.pzhuweb.sgblog.domain.utils.RedisCache;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 鄧浩奇
 * @classname ViewCountRunner
 * @description 在项目启动时执行的代码;把数据库中的浏览量存入redis中
 * @since 2023/7/25 21:10
 **/


/*
 * CommandLineRunner接口 实现项目启动时预处理
 * */

@Component
public class ViewCountRunner implements CommandLineRunner {

    @Resource
    private RedisCache redisCache;

    @Resource
    private ArticleService articleService;


    @Override
    public void run(String... args) throws Exception {
        // 查询所有文章的浏览量
        List<Article> articleList = articleService.list();
        Map<String, Integer> viewCount = new HashMap<>();
        for (Article article : articleList) {
            viewCount.put(article.getId().toString(),article.getViewCount().intValue());
        }
        // 存入redis
        redisCache.setCacheMap("article", viewCount);
    }


}
